package com.real;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.adapter.WordAdapter;
import com.entity.Word;
import com.util.Function;
import com.util.Internet;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: real
 * Date: 12-7-17
 * Time: 下午8:44
 * To change this template use File | Settings | File Templates.
 */
public class PushedWordsActivity extends Activity {

    public static List<Word> getWords()
    {
        return words;
    }

    static List<Word> words = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pushed_words);


        Calendar today = Calendar.getInstance();
//        String url = String.format("http://wordservertest.duapp.com/dailywords/%04d/%02d/%02d/",
//                today.get(Calendar.YEAR), 1 + today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH));
        String url = "http://wordservertest.duapp.com/dailywords/2012/07/21/";

        String s = "";
        try {
            s = Internet.getString(url);
        }catch(Exception e)
        {
            Toast.makeText(this, "连接服务器出错，请检查网络是否异常", Toast.LENGTH_LONG).show();
        }

        ArrayList<Word> wordslist = new ArrayList<Word>();
        WordAdapter adapter = new WordAdapter(this);
        try{
            JSONObject jsonObj = new JSONObject(s);
            JSONArray jsonWords = jsonObj.getJSONArray("words");

            for(int i=0; i<jsonWords.length(); i++){
                JSONObject json = jsonWords.getJSONObject(i);

                Word word = Word.parseJson(json);
                adapter.add(word);
                wordslist.add(word);
            }

            ListView list = (ListView)this.findViewById(R.id.pushed_words_listView);
            list.setAdapter(adapter);
            words = wordslist;
        }
        catch(Exception e){
            Toast.makeText(this, "服务器返回数据异常", Toast.LENGTH_LONG).show();
            return;
        }
    }

    public void onClick(View view){
        switch (view.getId()){
            case R.id.button_study:
                Function.SwitchActivity(this, StudyWordActivity.class);
                break;
        }
    }
}